package netty.rpc.core;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import netty.rpc.core.HessianSerialization;

/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2022/5/11 0:32
 */
public class RpcEncode extends MessageToByteEncoder {

    private Class<?> targetClass;

    public RpcEncode(Class<?> targetClass){
        this.targetClass = targetClass;
    }


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (targetClass.isInstance(o)){
            byte[] bytes = HessianSerialization.serialize(o);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
